import React,{Component} from 'react';
import {connect} from 'react-redux';
import { fetchList,addToCart,addToDetail } from '../actions'
import { Container, Row, Col } from 'reactstrap';
import { Button } from 'reactstrap';
import { NavLink as NLink } from 'react-router-dom';

const mapStateToProps = (state)=>{
  //console.log(state.list);
  return {
      rows: state.counter.list.rows,
      total:state.counter.list.total
  }
}

class Product extends Component{
  componentDidMount(){
    this.props.fetchList();
  }
  showPages(){
    var pages=Math.ceil(this.props.total/8);
    var jsx=[];
    for(let i=1;i<=pages;i++){
      jsx.push(
        <li className="page-item" key={i} onClick={()=>this.changePages(i)}><a className="page-link" href="javascript:void(0)">{i}</a></li>
      )
    }
    return jsx;
  }
  changePages=(page)=>{
    //console.log(page);
    this.props.fetchList({page})
  }
  addToCarts=(product)=>{
    //console.log(product);
    this.props.addToCart(product)
  }

  addToDetails=(product)=>{
    //console.log(product);
    this.props.addToDetail(product)
  }


  showRows(){
    var jsx=[];
    this.props.rows.map((item,index)=>{
      var details="product/"+item.id;
      jsx.push(<li key={index} className="productList">
          <img src={item.img} width="100" height="100"/>
          <p>{item.title}</p>
          <span>￥&nbsp;{item.price}</span>
          {/* <button onClick={()=>this.addToCarts(item)}>加入购物车</button> */}
          {/* <Button outline color="danger" onClick={()=>this.addToCarts(item)}>加入购物车</Button> */}
          <Button outline color="danger" className="viewBtn">
          <NLink to={details} onClick={()=>this.addToDetails(item)} className="view">View</NLink></Button>
      </li>) ;
    })
    return jsx;
  }

  render(){
    const {rows,total} =this.props; 
    return (
      <div className="products">
        <p className="allProduct">全部商品</p>
        <ul className="listsmsg">
          {this.showRows()}
        </ul>
        <nav aria-label="Page navigation example">
          <ul className="pagination justify-content-center">
            {this.showPages()}
          </ul>
        </nav>
      </div>
    )
  }
}

export default connect(mapStateToProps,{fetchList,addToCart,addToDetail})(Product);